import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Equal, In, Repository } from "typeorm";
import { MediaInfoEntity } from "../entity/info";
import { AddMediaDTO, ListMediaDTO } from "../dto/info";
import { Context } from "@midwayjs/koa";
import { ProviderTeamEntity } from "../../provider/entity/team";
import { ProviderProfileEntity } from "../../provider/entity/profile";
import { CapacityEntity } from "../../transport/entity/capacity";
import * as http from 'http';
import * as https from 'https';
import * as fs from 'fs/promises';
import * as path from 'path';

@Provide()
export class MediaInfoService extends BaseService {
  @InjectEntityModel(MediaInfoEntity)
  mediaModel: Repository<MediaInfoEntity>;

  @InjectEntityModel(ProviderTeamEntity)
  teamModel: Repository<ProviderTeamEntity>;

  @InjectEntityModel(ProviderProfileEntity)
  profileModel: Repository<ProviderProfileEntity>;

  @InjectEntityModel(CapacityEntity)
  capacityModel: Repository<CapacityEntity>;

  @Inject()
  ctx: Context;

  /** 计算当前用户 teamId（优先拥有团队，其次所属团队），可能返回 null */
  private async resolveCurrentTeamId(providerId: number): Promise<number | null> {
    const ownerTeam = await this.teamModel.findOne({ where: { ownerProviderId: Equal(providerId) } });
    if (ownerTeam) return ownerTeam.id;
    const profile = await this.profileModel.findOne({ where: { providerId: Equal(providerId) } });
    if (!profile) return null;
    const capacity = await this.capacityModel.findOne({ where: { id: Equal(profile.capacityId) } });
    return capacity?.teamId ?? null;
  }

  /** 通过 URL 尝试检测资源大小（字节）。支持 http/https HEAD；本地路径尝试 stat。失败返回 undefined */
  private async detectSizeByUrl(resourceUrl: string): Promise<number | undefined> {
    try {
      if (!resourceUrl) return undefined;
      const isHttp = resourceUrl.startsWith('http://');
      const isHttps = resourceUrl.startsWith('https://');
      if (isHttp || isHttps) {
        const mod = isHttps ? https : http;
        return await new Promise<number | undefined>((resolve) => {
          const req = mod.request(resourceUrl, { method: 'HEAD' }, (res) => {
            const len = res.headers['content-length'];
            const size = Array.isArray(len) ? parseInt(len[0]) : len ? parseInt(len) : undefined;
            resolve(Number.isFinite(size as number) ? size : undefined);
          });
          req.on('error', () => resolve(undefined));
          req.end();
        });
      }
      // 尝试本地文件（相对路径按项目根目录解析）
      const filePath = path.isAbsolute(resourceUrl) ? resourceUrl : path.join(process.cwd(), resourceUrl);
      const stat = await fs.stat(filePath).catch(() => undefined as any);
      return stat?.isFile() ? stat.size : undefined;
    } catch {
      return undefined;
    }
  }

  /** 新增我的媒体资源（同时绑定 providerId、teamId） */
  async addByProviderId(dto: AddMediaDTO, providerId: number) {
    if (!providerId) throw new CoolCommException('未登录或缺少服务人员信息');
    const teamId = await this.resolveCurrentTeamId(providerId);

    // 若未提供 size，尝试自动检测
    const autoSize = dto.size ?? await this.detectSizeByUrl(dto.url);

    return await this.mediaModel.save({
      providerId,
      teamId: teamId ?? null,
      ...dto,
      size: autoSize,
    });
  }

  /** 我的媒体资源列表（可按类型筛选） */
  async listByProviderId(query: ListMediaDTO, providerId: number) {
    const where: any = { providerId: Equal(providerId) };
    if (query?.type) where.type = Equal(query.type);
    return this.mediaModel.find({ where, order: { id: 'DESC' } });
  }


  /** 当前团队媒体资源（团队所有者可见团队内全部；成员可见所属团队内全部） */
  async teamListByProviderId(query: ListMediaDTO, providerId: number) {
    const teamId = await this.resolveCurrentTeamId(providerId);
    if (!teamId) return [];
    const where: any = { teamId: Equal(teamId) };
    if (query?.type) where.type = Equal(query.type);
    return this.mediaModel.find({ where, order: { id: 'DESC' } });
  }

  /** 删除媒体：本人可删自己的；团队所有者可删团队下任何人的 */
  async delete(ids: number[] | number) {
    const providerId = this.ctx.provider?.id;
    if (!providerId) throw new CoolCommException('未登录或缺少服务人员信息');
    const idList = Array.isArray(ids) ? ids : [ids];
    if (!idList.length) return;
    const records = await this.mediaModel.find({ where: { id: In(idList) } });
    if (!records.length) throw new CoolCommException('媒体资源不存在');
    const ownerTeam = await this.teamModel.findOne({ where: { ownerProviderId: Equal(providerId) } });
    const permitted = ownerTeam
      ? records.filter(r => r.teamId === ownerTeam.id)
      : records.filter(r => r.providerId === providerId);
    if (permitted.length !== records.length) {
      throw new CoolCommException('存在无权限删除的媒体资源');
    }
    await this.mediaModel.delete(permitted.map(p => p.id));
  }
}


